package com.app.couponsharelife.ui.main.home.search

import android.content.Context
import android.view.inputmethod.EditorInfo
import android.widget.LinearLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.google.gson.Gson
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.SearchHistoryBean
import com.app.couponsharelife.ui.view.ScaleTransitionPagerTitleView
import com.app.couponsharelife.utils.AppUtils
import kotlinx.android.synthetic.main.activity_homesearch.*
import kotlinx.android.synthetic.main.base_title_search_white.*
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator

/**
 *Created by xct on 2019/1/9
 *Description:搜索结果页面
 */
class HomeSearchActivity:BaseActivity() {
    private var titleList:ArrayList<String>?=null
    private var commonNavigator: CommonNavigator?=null
    private var mPagers = arrayListOf<Fragment>()
    var keyword=""
    private var pageIndex=0
    private var searchType=""
    private var historyList= arrayListOf<String>()
    override val viewLayoutId: Int
        get() = R.layout.activity_homesearch
    override fun initViews() {
        AppUtils.initImmersionBar(this,true)
        keyword=intent.getStringExtra("KeyWord")?:""
        searchType=intent.getStringExtra("SearchType")?:""
        basetitle_edit.setText(keyword)
        basetitle_edit.setSelection(keyword.length)
        val keys=AppUtils.getString("searchKey", "")
        historyList.clear()
        basetitle_tvZW.post {
            val layoutparams=basetitle_tvZW.layoutParams as LinearLayout.LayoutParams
            layoutparams.width=AppUtils.getDisplayMetrics(this).widthPixels
            layoutparams.height=AppUtils.getStatusBarHeight(this)
            basetitle_tvZW.layoutParams=layoutparams
        }
        if (keys.isNotEmpty()){
            historyList.addAll(Gson().fromJson(keys, SearchHistoryBean::class.java).list?: arrayListOf())
        }
        setViewPager()
        basetitle_llclose.setOnClickListener { finish() }
        basetitle_edit.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH){
                val keyWord=basetitle_edit.text.toString().trim()
                if (keyWord.isNotEmpty()){
                    setKey(keyWord)
                    if (0==pageIndex){
                        (mPagers[0] as SearchTaobaoFragment).refreshData(keyWord)
                    }else{
                        (mPagers[1] as SearchPDDFragment).refreshData(keyWord)
                    }
                    AppUtils.hideInputBoard(this,basetitle_edit)
                }else{
                    showToastMsg("请输入搜索内容！")
                }
                true
            }else{
                false
            }
        }
        basetitle_imag_delete.setOnClickListener { basetitle_edit.setText("") }
    }
    private fun setViewPager(){
        titleList= ArrayList()
        titleList!!.add("淘宝／天猫券")
        titleList!!.add("拼多多券")
        mPagers.add(SearchTaobaoFragment.newInstance())
        mPagers.add(SearchPDDFragment.newInstance())
        homesearch_viewpager.adapter=object : FragmentPagerAdapter(supportFragmentManager){
            override fun getItem(position: Int): Fragment {
                return mPagers[position]
            }

            override fun getCount(): Int {
                return titleList!!.size
            }

            override fun getPageTitle(position: Int): CharSequence? {
                return titleList!![position]
            }
        }
        commonNavigator= CommonNavigator(this)
        commonNavigator!!.isAdjustMode=true
        commonNavigator!!.adapter=object : CommonNavigatorAdapter(){
            override fun getTitleView(p0: Context, p1: Int): IPagerTitleView {
                val colorTransitionPagerTitleView= ScaleTransitionPagerTitleView(p0,1f)
                colorTransitionPagerTitleView.normalColor = resources.getColor(R.color.gray99)
                colorTransitionPagerTitleView.textSize=16f
                colorTransitionPagerTitleView.paint.isFakeBoldText=true
                colorTransitionPagerTitleView.selectedColor = resources.getColor(R.color.act_main_bot_nav_select_text_color)
                colorTransitionPagerTitleView.text = titleList!![p1]
                colorTransitionPagerTitleView.setOnClickListener { homesearch_viewpager.currentItem = p1 }
                return colorTransitionPagerTitleView
            }

            override fun getCount(): Int {
                return titleList!!.size
            }

            override fun getIndicator(p0: Context?): IPagerIndicator? {
                val indicator= LinePagerIndicator(p0)
                indicator.setColors(resources.getColor(R.color.act_main_bot_nav_select_text_color))
                indicator.mode=LinePagerIndicator.MODE_WRAP_CONTENT
                return indicator
            }
        }
        homesearch_viewpager.addOnPageChangeListener(object :ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                pageIndex=position
            }
        })
        homesearch_tablayout.navigator=commonNavigator
        ViewPagerHelper.bind(homesearch_tablayout, homesearch_viewpager)
        if ("TB"!=searchType){
            homesearch_viewpager.setCurrentItem(1,false)
        }
    }
    private fun setKey(keyWord:String){
        if (!historyList.contains(keyWord)){
            if (historyList.size>=10){
                historyList.removeAt(9)
                historyList.add(0,keyWord)
            }else{
                historyList.add(0,keyWord)
            }
        }
        AppUtils.setString("searchKey", Gson().toJson(SearchHistoryBean(historyList)))
    }
    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
}